import React, {PureComponent} from 'react';
import {
  View,
  Text,
  TextInput,
  Keyboard,
  KeyboardAvoidingView,
  Platform,
  TouchableOpacity,
  ScrollView,
  Linking,
  AppState,
} from 'react-native';
import Clipboard from '@react-native-community/clipboard';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {TextButton, LinearButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import QRCode from 'react-native-qrcode-svg';
import LayoutConstants from '../../config/LayoutConstants';
import {showToast} from '../../components/Toast';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {queryWalltBalance} from '../../redux/action/index';
import {LinerBoardTextInput} from '../../components/TextInput';

class WalletScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      password: '',
      swht: 0,
      ht: 0,
      connector: undefined,
    };
  }

  componentDidMount() {
    this.props.queryWalltBalance();

    // Linking.getInitialURL().then((url) => {
    //   console.log('*****' + url);
    // });
    // Linking.addEventListener('url', this.appWork);
    //App进程启动后的监听
    this.listenAppState = AppState.addEventListener(
      'change',
      this.handleAppStateChange,
    );
    //App 激活状态下进行的跳转
    this.linkingListen = Linking.addEventListener('url', (event) =>
      this.handleOpenURL(event.url),
    );
  }

  componentWillUnmount() {
    if (this.listenAppState) {
      this.listenAppState.remove();
    }

    if (this.linkingListen) {
      this.linkingListen.remove();
    }
  }

  handleAppStateChange = (nextAppState) => {
    if (nextAppState === 'active') {
      Linking.getInitialURL().then((url) => {
        console.log('跳转的url为' + url);
      });
    }
  };

  handleOpenURL = (url) => {
    console.log('---跳转的url为' + url);
  };

  handleSessionUserApproval = async (approved, proposal) => {
    if (approved) {
      // if user approved then include response with accounts matching the chains and wallet metadata
      const response = {
        state: {
          accounts: ['eip155:1:0x1d85568eEAbad713fBB5293B45ea066e552A90De'],
        },
      };
      await client.approve({proposal, response});
    } else {
      // if user didn't approve then reject with no response
      await client.reject({proposal});
    }
  };

  linkToWallet = async () => {
    // Linking.openURL(
    //   'https://metamask.app.link/wc?uri=wc:2f882179-82e3-42e1-8199-00099cd10f50@1?bridge=https%3A%2F%2Fv.bridge.walletconnect.org&key=d5ae8d9774f6f863e39519d506f8e9f9275ff09a1ab6b6eabce23ac7a9e3cd08',
    // );
    // return;
    Linking.openURL(
      'https://metamask.app.link/dapp/deesse.art/source/approve.html',
    );

    return;

    // 当DApp连接上钱包后，若钱包的信息发生变化（大部分情况是 chainId 或者 address），会触发 session_update 的回调
    connector.on('session_update', async (error, payload) => {
      console.log(`connector.on("session_update")`, payload);

      if (error) {
        throw error;
      }

      const {chainId, accounts} = payload.params[0];

      // 通过 payload.params 拿到 accounts 和 chainId，对 DApp 的 state 进行更新
      // this.onSessionUpdate(accounts, chainId);
    });

    connector.on('connect', (error, payload) => {
      console.log(`connector.on("connect")`, payload);

      if (error) {
        throw error;
      }

      // this.onConnect(payload);
    });

    connector.on('disconnect', (error, payload) => {
      console.log(`connector.on("disconnect")`, payload);

      if (error) {
        throw error;
      }

      // this.onDisconnect();
    });

    // 如果已经连接，则 walletConnectInit 执行后不会唤起二维码弹框，只需进行 DApp 的 state更新
    if (connector.connected) {
      const {chainId, accounts} = connector;
      const address = accounts[0];
      this.setState({
        connected: true,
        chainId,
        accounts,
        address,
      });
      // this.onSessionUpdate(accounts, chainId);
    }

    return;

    // // Create connector
    // const client = await WalletConnectClient.init({
    //   controller: true,
    //   projectId: '4b261eec4716ad67dabc071880d00561',
    //   relayUrl: 'wss://relay.walletconnect.com',
    //   metadata: {
    //     name: 'Signin Club',
    //     description: 'Signin Club',
    //     url: 'https://signin.art',
    //     icons: ['https://walletconnect.com/walletconnect-logo.png'],
    //   },
    //   storageOptions: {
    //     asyncStorage: AsyncStorage,
    //   },
    // });

    // console.log(client);

    // client.on(CLIENT_EVENTS.session.proposal, async (proposal) => {
    //   // console.log(proposal);
    //   console.log('--------');
    //   // user should be prompted to approve the proposed session permissions displaying also dapp metadata
    //   const {proposer, permissions} = proposal;
    //   const {metadata} = proposer;

    //   console.log(proposal);

    //   let approved = false;
    //   this.handleSessionUserApproval(approved, proposal); // described in the step 4
    // });

    // client.on(CLIENT_EVENTS.session.created, async (session) => {
    //   // session created succesfully
    //   console.log('session');
    // });

    // client.pair({
    //   uri:
    //     'wc:f3a47d82d88fe227f7dc76cd11f0aa3e2b410fae51943966156201d32dc88c77@2?controller=false&publicKey=1e641d2e8c2d00fc971df0550358f617813cae31c6d8c2fb58f98214b4356757&relay=%7B%22protocol%22%3A%22waku%22%7D',
    // });
    // client.pair(`wc:f3a47d82d88fe227f7dc76cd11f0aa3e2b410fae51943966156201d32dc88c77@2?controller=false&publicKey=1e641d2e8c2d00fc971df0550358f617813cae31c6d8c2fb58f98214b4356757&relay=%7B%22protocol%22%3A%22waku%22%7D`);
  };

  _exportPrivateKey = async () => {
    if (this.state.password.length == 0) {
      this._showAlert({
        content: 'please input password!',
      });
      return;
    }

    this._showLoading('decoding...');
    try {
      let pk = await WalletUtils.privateKeyOfKeystore(
        this.props.userInfo.keystore,
        this.state.password,
      );
      console.log(pk);
      Clipboard.setString(pk);
      showToast('Copied!', undefined, 3000);
    } catch (err) {
      this._showAlert({
        content: 'password error',
      });
    }
    this._hideLoading();
  };

  renderComponent = () => {
    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Wallet"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{flex: 1}}>
          <ScrollView style={{flex: 1}}>
            <TouchableOpacity onPress={this.linkToWallet}>
              <Text style={{color: 'white'}}>META MASK</Text>
            </TouchableOpacity>
            <View
              style={{
                margin: 20,
                backgroundColor: 'white',
                borderRadius: 10,
                padding: 20,
              }}>
              <Text
                style={{
                  fontSize: 18,
                  color: '#7304F3',
                  fontWeight: 'bold',
                  marginBottom: 20,
                }}>
                Balance
              </Text>
              {this.props.coins.map((item) => {
                return (
                  <View
                    key={item.symbol}
                    style={{
                      width: '100%',
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                      borderBottomColor: 'rgba(220,220,220,0.8)',
                      borderBottomWidth: 1,
                      borderBottomStyle: 'solid',
                      paddingTop: 10,
                      paddingBottom: 10,
                    }}>
                    <Text
                      style={{
                        fontSize: 18,
                        color: '#7104F4',
                      }}>
                      {item.symbol}
                    </Text>
                    <Text
                      style={{
                        fontSize: 18,
                        color: '#A1A1A1',
                      }}>
                      {`${
                        item.balance ? item.balance : 0
                      }  ${item.symbol.toLowerCase()}`}
                    </Text>
                  </View>
                );
              })}
              <LinearButton
                text={'Convert'}
                buttonStyle={{
                  flex: 1,
                }}
                onPress={() => {
                  this.props.navigation.navigate('ConvertHT');
                }}></LinearButton>
            </View>
            <View
              style={{
                margin: 20,
                backgroundColor: 'white',
                borderRadius: 10,
                padding: 20,
              }}>
              <Text
                style={{
                  fontSize: 18,
                  color: '#7304F3',
                  fontWeight: 'bold',
                  marginBottom: 20,
                }}>
                Wallet Address
              </Text>
              <View
                style={{
                  padding: 20,
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <QRCode
                  size={LayoutConstants.WINDOW_WIDTH - 160}
                  backgroundColor="#A1A1A1"
                  color="white"
                  value={this.props.userInfo.address}
                />
              </View>
              <LinearButton
                text={I18n.t('user.copy')}
                onPress={() => {
                  Clipboard.setString(this.props.userInfo.address);
                  showToast('Copied!', undefined, 3000);
                }}
              />
            </View>
            <View
              style={{
                margin: 20,
                backgroundColor: 'white',
                borderRadius: 10,
                padding: 20,
                marginTop: 20,
              }}>
              <Text
                style={{
                  fontSize: 18,
                  color: '#7304F3',
                  fontWeight: 'bold',
                  marginBottom: 30,
                }}>
                Wallet Private Key
              </Text>
              <LinerBoardTextInput
                placeholder={I18n.t('login.password')}
                placeholderTextColor="#a1a1a1"
                secureTextEntry
                onChangeText={(text) => {
                  this.setState({
                    password: text,
                  });
                }}></LinerBoardTextInput>
              <LinearButton
                text={I18n.t('user.export')}
                onPress={this._exportPrivateKey}
              />
            </View>
            <View
              style={{
                width: '100%',
                height: this.props.widgetLayout.show
                  ? this.props.widgetLayout.height
                  : 0,
                marginTop: 10,
              }}></View>
          </ScrollView>
        </KeyboardAvoidingView>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  coins: state.Chain.coins,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  queryWalltBalance: () => dispatch(queryWalltBalance()),
});

export default connect(mapStateToProps, mapDispatchToProps)(WalletScreen);
